package jsyf.oa.service.task;

import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.DateUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.system.RegionDao;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.dao.task.BonusDao;
import jsyf.oa.entity.task.BonusEntity;
import jsyf.oa.facade.task.BonusFacade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class BonusRemindService implements BonusFacade {
    @Autowired
    private RegionDao regionDao;
    @Autowired
    private BonusDao bonusDao;
    @Autowired
    private UserDao userDao;

    @Override
    public List<JSONObject> getBonus(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String date = jsonParams.getString("dateTime");
        String companyId = jsonParams.getString("companyId");
        String bigRegionId = jsonParams.getString("bigRegionId");
        String roleName = jsonParams.getString("roleName");
        String userId = jsonParams.getString("userId");
        if (StringUtils.isBlank(date)) {
            date = DateUtils.nowDateByString(new Date()).substring(0, 10);
        }
        if (StringUtils.isBlank(userId)) {
            userId = "";
        }
        List<Object> sqlArgs = new ArrayList<Object>();
        sqlArgs.add("%" + date + "%");
        sqlArgs.add(userId);
        sqlArgs.add(companyId);
        sqlArgs.add(roleName);
        String roleNames="总经理，销售总监，区域总监";
        if (roleNames.indexOf(roleName)!=-1){
            return bonusDao.getJSONListByCondition("  AND DAY LIKE ? AND USER_ID=? AND COMPANY_ID=? AND ROLE_NAME=? AND TYPE=0  ORDER BY `DAY` DESC", sqlArgs.toArray());
        }else{
            sqlArgs.add(bigRegionId);
            return bonusDao.getJSONListByCondition("  AND DAY LIKE ? AND USER_ID=? AND COMPANY_ID=?  AND ROLE_NAME=? AND BIG_REGION_ID=? AND TYPE=0  ORDER BY `DAY` DESC", sqlArgs.toArray());
        }
    }

    @Override
    public Boolean updateBonusMoney(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);

        String date = DateUtils.nowDateByString(new Date()).substring(0, 10);
        String type="";
        String regionId="";
        String userId="";
        String condition="";
        //先获取所有大区以及他的配置数；"
        if (jsonParams.containsKey("type")) {
            StringBuffer sbcondition=new StringBuffer();
            type = jsonParams.getString("type");
            if (type.equals("1")){
                regionId= jsonParams.getString("regionIds");
            }else{
                userId = jsonParams.getString("userId");
                List<JSONObject> regionList= regionDao.getRegionByUserId(userId);
                if (regionList!=null&&regionList.size()>0){
                    for (int i=0;i<regionList.size();i++){
                        sbcondition.append("'");
                        sbcondition.append(regionList.get(i).getString("id"));
                        sbcondition.append("'");
                        sbcondition.append(",");
                    }
                    regionId=sbcondition.toString().substring(0,sbcondition.toString().length()-1);
                }

            }

            if (regionId!=null&&!"".equals(regionId)){
                condition=" AND t_sys_region.ID in("+regionId+")";
            }

        }
        List<JSONObject> regions = regionDao.getBigRegion(condition);//获得所有大区大区经理标配，区域经理标配
        for (int i = 0; i < regions.size(); i++) {
            bonusDao.removeByCondition(" and day=? and type=0 and BIG_REGION_ID =?", new String[]{date,regions.get(i).getString("id")});
            int regionCount = 0;
            int bigRegionCount = 0;
            int bigRegionCountTarget = Integer.parseInt(regions.get(i).getString("bigManagerTarget"));//标配大区经理数目
            int regionCountTarget = Integer.parseInt(regions.get(i).getString("managerTarget"));//标配区域经理数目
            //获取每个大区应该有的区域经理，大区经理数
            regionCount = Integer.parseInt(regionDao.getCount("'区域经理','区域组长'", regions.get(i).getString("id"), regions.get(i).getString("companyId"), regions.get(i).getString("name")).getString("userNum"));
            bigRegionCount = Integer.parseInt(regionDao.getCount("'大区经理'", regions.get(i).getString("id"), regions.get(i).getString("companyId"), regions.get(i).getString("name")).getString("userNum"));
            int subBigRegionCount = bigRegionCountTarget - bigRegionCount;//大区经理差值
            int subRegionCount = regionCountTarget - regionCount;//区域经理差值
            BonusEntity bonusEntity = new BonusEntity();
            //缺少区域经理，扣钱
            //缺少区域经理，大区经理  -->  罚款12元
            //缺少区域经理，---> 销售总监 / 总经理 / 区域总监  都是扣款4元
            if (regions.get(i).getString("name").equals("铜池大区")){
                System.out.println(regions.get(i).getString("name"));
            }
            if (subRegionCount > 0) {
                //缺少区域经理 --> 大区经理扣钱

                //查询该大区下的哪几个区域缺少区域经理
                StringBuilder regionNameList=new StringBuilder();
                String regionNames="";
                List<JSONObject>  minRegionList=regionDao.getLackRegion("'区域经理','区域组长'", regions.get(i).getString("id"), regions.get(i).getString("companyId"), regions.get(i).getString("name"));
                if (minRegionList!=null&&minRegionList.size()>0){
                    for (JSONObject regionInfo:minRegionList){
                        regionNameList.append("【");
                        regionNameList.append(regionInfo.getString("regionName"));
                        regionNameList.append("】，");
                    }
                    regionNames=regionNameList.toString();
                }
                List<JSONObject> bigRegion = regionDao.getBigRegionByRoleName("大区经理", regions.get(i).getString("id"), regions.get(i).getString("companyId"), regions.get(i).getString("name"));
                if (null != bigRegion && bigRegion.size() > 0) {
                    bonusEntity.setCompanyId(regions.get(i).getString("companyId"));
                    bonusEntity.setBigRegionId(regions.get(i).getString("id"));
                    bonusEntity.setUserId(bigRegion.get(0).getString("userId"));
                    bonusEntity.setMoney(new BigDecimal(12 * subRegionCount));
                    bonusEntity.setDay(date);
                    bonusEntity.setType(0);
                    bonusEntity.setRoleName("大区经理");
                   // bonusEntity.setRemark(regions.get(i).getString("name") + "缺少" + subRegionCount + "个区域经理，罚款" + bonusEntity.getMoney());
                   bonusEntity.setRemark(regions.get(i).getString("name") +"-"+regionNames+"缺少" + subRegionCount + "个区域经理，罚款" + bonusEntity.getMoney());
                    //String bonuEntity = JSON.toJSONString(bonusEntity);
                    bonusDao.add(bonusEntity);
                }
                //缺少区域经理，---> 区域总监/ 销售总监 / 总经理   扣钱
                //获取该公司下的区域总监
                StringBuffer stringBuffer=new StringBuffer();
                stringBuffer.append("''");
                stringBuffer.append(",");
                if (null != bigRegion && bigRegion.size() > 0) {
                    stringBuffer.append("'");
                    stringBuffer.append(bigRegion.get(0).getString("userId"));
                    stringBuffer.append("'");
                    stringBuffer.append(",");
                }
                String QyUser=stringBuffer.toString();
                QyUser=QyUser.substring(0,QyUser.length()-1);
                List<JSONObject> QyDirector =regionDao.getDirectorByCompanyId("区域总监",regions.get(i).getString("companyId"),QyUser,regions.get(i).getString("id"));
                if (null != QyDirector && QyDirector.size() > 0) {
                    for (int j = 0; j < QyDirector.size(); j++) {
                        BonusEntity bonus = new BonusEntity();
                        bonus.setCompanyId(regions.get(i).getString("companyId"));
                        bonus.setBigRegionId(regions.get(i).getString("id"));
                        bonus.setUserId(QyDirector.get(j).getString("userId"));
                        stringBuffer.append("'");
                        stringBuffer.append(QyDirector.get(j).getString("userId"));
                        stringBuffer.append("'");
                        stringBuffer.append(",");
                        bonus.setMoney(new BigDecimal(4 * subRegionCount));
                        bonus.setDay(date);
                        bonus.setType(0);
                        bonus.setRoleName("区域总监");
                       // bonus.setRemark(regions.get(i).getString("name") + "缺少" + subRegionCount + "个区域经理，罚款" + bonus.getMoney());
                        bonus.setRemark(regions.get(i).getString("name") + "-"+regionNames+"缺少" + subRegionCount + "个区域经理，罚款" + bonus.getMoney());
                        bonusDao.add(bonus);
                    }
                }
                //获取该公司下的销售总监
                String XsUser=stringBuffer.toString();
                XsUser=XsUser.substring(0,XsUser.length()-1);
                List<JSONObject> XsDirector =regionDao.getDirectorByCompanyId("销售总监",regions.get(i).getString("companyId"),XsUser,regions.get(i).getString("id"));
                if (null != XsDirector && XsDirector.size() > 0) {
                    for (int j = 0; j < XsDirector.size(); j++) {
                        BonusEntity bonus = new BonusEntity();
                        bonus.setCompanyId(regions.get(i).getString("companyId"));
                        bonus.setBigRegionId(regions.get(i).getString("id"));
                        bonus.setUserId(XsDirector.get(j).getString("userId"));
                        stringBuffer.append("'");
                        stringBuffer.append(XsDirector.get(j).getString("userId"));
                        stringBuffer.append("'");
                        stringBuffer.append(",");
                        bonus.setMoney(new BigDecimal(4 * subRegionCount));
                        bonus.setDay(date);
                        bonus.setType(0);
                        bonus.setRoleName("销售总监");
                      //  bonus.setRemark(regions.get(i).getString("name") + "缺少" + subRegionCount + "个区域经理，罚款" + bonus.getMoney());
                        bonus.setRemark(regions.get(i).getString("name") + "-'"+regionNames+"缺少" + subRegionCount + "个区域经理，罚款" + bonus.getMoney());
                        bonusDao.add(bonus);
                    }
                }


                //获取该公司下的总经理
                String JlUser=stringBuffer.toString();
                JlUser=JlUser.substring(0,JlUser.length()-1);
                List<JSONObject> JlDirector =regionDao.getDirectorByCompanyId("总经理",regions.get(i).getString("companyId"),JlUser,regions.get(i).getString("id"));
                if (null != JlDirector && JlDirector.size() > 0) {
                    for (int j = 0; j < JlDirector.size(); j++) {
                        BonusEntity bonus = new BonusEntity();
                        bonus.setCompanyId(regions.get(i).getString("companyId"));
                        bonus.setBigRegionId(regions.get(i).getString("id"));
                        bonus.setUserId(JlDirector.get(j).getString("userId"));
                        stringBuffer.append("'");
                        stringBuffer.append(JlDirector.get(j).getString("userId"));
                        stringBuffer.append("'");
                        stringBuffer.append(",");
                        bonus.setMoney(new BigDecimal(4 * subRegionCount));
                        bonus.setDay(date);
                        bonus.setType(0);
                        bonus.setRoleName("总经理");
                      //  bonus.setRemark(regions.get(i).getString("name") + "缺少" + subRegionCount + "个区域经理，罚款" + bonus.getMoney());
                        bonus.setRemark(regions.get(i).getString("name")+ "-"+regionNames+"缺少" + subRegionCount + "个区域经理，罚款" + bonus.getMoney());
                        bonusDao.add(bonus);
                    }
                }
            }
            //缺少大区经理 ---> 销售总监 / 总经理 / 区域总监  都是扣款12元
            if (subBigRegionCount > 0) {
                //获取该公司下的区域总监
                StringBuffer stringBuffer=new StringBuffer();
                stringBuffer.append("''");
                stringBuffer.append(",");
                String QyUser=stringBuffer.toString();
                QyUser=QyUser.substring(0,QyUser.length()-1);
                List<JSONObject> QyDirector =regionDao.getDirectorByCompanyId("区域总监",regions.get(i).getString("companyId"),QyUser,regions.get(i).getString("id"));
                if (null != QyDirector && QyDirector.size() > 0) {
                    for (int j = 0; j < QyDirector.size(); j++) {
                        BonusEntity bonus = new BonusEntity();
                        bonus.setCompanyId(regions.get(i).getString("companyId"));
                        bonus.setBigRegionId(regions.get(i).getString("id"));
                        bonus.setUserId(QyDirector.get(j).getString("userId"));
                        stringBuffer.append("'");
                        stringBuffer.append(QyDirector.get(j).getString("userId"));
                        stringBuffer.append("'");
                        stringBuffer.append(",");
                        bonus.setMoney(new BigDecimal(12 * subBigRegionCount));
                        bonus.setDay(date);
                        bonus.setType(0);
                        bonus.setRoleName("区域总监");
                        bonus.setRemark(regions.get(i).getString("name") + "缺少" + subBigRegionCount + "个大区经理，罚款" + bonus.getMoney());
                        bonusDao.add(bonus);
                    }
                }
                //获取该公司下的销售总监
                String XsUser=stringBuffer.toString();
                XsUser=XsUser.substring(0,XsUser.length()-1);
                List<JSONObject> XsDirector =regionDao.getDirectorByCompanyId("销售总监",regions.get(i).getString("companyId"),XsUser,regions.get(i).getString("id"));
                if (null != XsDirector && XsDirector.size() > 0) {
                    for (int j = 0; j < XsDirector.size(); j++) {
                        BonusEntity bonus = new BonusEntity();
                        bonus.setCompanyId(regions.get(i).getString("companyId"));
                        bonus.setBigRegionId(regions.get(i).getString("id"));
                        bonus.setUserId(XsDirector.get(j).getString("userId"));
                        stringBuffer.append("'");
                        stringBuffer.append(XsDirector.get(j).getString("userId"));
                        stringBuffer.append("'");
                        stringBuffer.append(",");
                        bonus.setMoney(new BigDecimal(12 * subBigRegionCount));
                        bonus.setDay(date);
                        bonus.setType(0);
                        bonus.setRoleName("销售总监");
                        bonus.setRemark(regions.get(i).getString("name") + "缺少" + subBigRegionCount + "个大区经理，罚款" + bonus.getMoney());
                        bonusDao.add(bonus);
                    }
                }


                //获取该公司下的总经理
                String JlUser=stringBuffer.toString();
                JlUser=JlUser.substring(0,JlUser.length()-1);
                List<JSONObject> JlDirector =regionDao.getDirectorByCompanyId("总经理",regions.get(i).getString("companyId"),JlUser,regions.get(i).getString("id"));
                if (null != JlDirector && JlDirector.size() > 0) {
                    for (int j = 0; j < JlDirector.size(); j++) {
                        BonusEntity bonus = new BonusEntity();
                        bonus.setCompanyId(regions.get(i).getString("companyId"));
                        bonus.setBigRegionId(regions.get(i).getString("id"));
                        bonus.setUserId(JlDirector.get(j).getString("userId"));
                        stringBuffer.append("'");
                        stringBuffer.append(JlDirector.get(j).getString("userId"));
                        stringBuffer.append("'");
                        stringBuffer.append(",");
                        bonus.setMoney(new BigDecimal(12 * subBigRegionCount));
                        bonus.setDay(date);
                        bonus.setType(0);
                        bonus.setRoleName("总经理");
                        bonus.setRemark(regions.get(i).getString("name") + "缺少" + subBigRegionCount + "个大区经理，罚款" + bonus.getMoney());
                        bonusDao.add(bonus);
                    }
                }


            }
        }
        return true;
    }

}
